﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using X10Unified.Senders;
using System.IO.IsolatedStorage;

namespace X10Communicator
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args[0].Contains("?"))
            {
                showHelp();
                return;
            }

            if (args.Length == 1)
            {
                switch (args[0].ToLower())
                {
                    case "shutdown":
                        {
                            TurnOffLights(false);
                            return;
                        }
                    case "start":
                        {
                            List<DeviceSetting> list;
                            list = getSavedSettings();
                            if (list.Count == 0)
                            {
                                return;
                            }
                            Firecracker firecracker = Firecracker.GetInstance(1);
                            foreach (DeviceSetting item in list)
                            {
                                char hc = item.Key.Split('|')[0][0];
                                int dc;
                                int.TryParse(item.Key.Split('|')[1], out dc);

                                firecracker.SendCommand(hc, dc, (Firecracker.Commands)Enum.Parse(typeof(Firecracker.Commands), item.Command));
                            }
                            return;
                        }
                }
            }

            if (args.Length >= 3)
            {
                char hc = args[0].Split(':')[1].ToCharArray(0,1)[0];
                int dc; 
                int.TryParse(args[1].Split(':')[1], out dc);
                int c;
                int.TryParse(args[2].Split(':')[1], out c);

                if (args.Length > 3)
                {
                    foreach(string arg in args)
                    {
                        if (arg == "TurnOffOtherDevices")
                        {
                            TurnOffLights(true);
                        }
                    }
                }

                Firecracker.Commands command;

                if (c == 1)
                {
                    command = Firecracker.Commands.TurnOn;
                }
                else if (c == 0)
                {
                    command = Firecracker.Commands.TurnOff;
                }
                else
                {
                    return;
                }

                UpdateList(hc, dc, command);


                Firecracker firecracker = Firecracker.GetInstance(1);
                //send a command to the device
                firecracker.SendCommand(hc, dc, command);
                return;
             }

            showHelp();
            return;

        }

        private static void UpdateList(char hc, int dc, Firecracker.Commands command)
        {
            List<DeviceSetting> list;

            list = getSavedSettings();

            string key = hc + "|" + dc;
            bool added = false;

            if(list.Count == 0) // || (!list.Contains(turnoff) && !list.Contains(turnon)))
            {
                 list.Add(new DeviceSetting(key, command.ToString()));            
            }
            else
            {
                foreach (DeviceSetting item in list)
                {
                    if(item.Key == key)
                    {
                        list.Remove(item);
                        if(command == Firecracker.Commands.TurnOn)
                        {
                        list.Add(new DeviceSetting(key, command.ToString()));
                        }
                        added = true;
                        break;
                    }
                }
                if (!added && command == Firecracker.Commands.TurnOn)
                {
                    list.Add(new DeviceSetting(key, command.ToString()));  
                }

            }

            saveSettings(list);
        }

        private static List<DeviceSetting> getSavedSettings()
        {
            List<DeviceSetting> list = new List<DeviceSetting>();
            
            IsolatedStorageFile isoStorage;
            isoStorage = IsolatedStorageFile.GetUserStoreForAssembly();


            string[] isoFileNames;

            isoFileNames = isoStorage.GetFileNames("X10Communicator.xml");

            foreach(string isoFile in isoFileNames)
            {
                if(isoFile == "X10Communicator.xml")
                {
                     XmlSerializer isoSerializer = new XmlSerializer(list.GetType());
                     StreamReader isoStreamReader = new StreamReader(new IsolatedStorageFileStream("X10Communicator.xml", FileMode.Open, isoStorage));
                     list = (List<DeviceSetting>)isoSerializer.Deserialize(isoStreamReader);
                     isoStreamReader.Close();
                }
            }
            
            return list;

        }

        private static void saveSettings(List<DeviceSetting> list)
        {
            IsolatedStorageFile isoStorage;
            isoStorage = IsolatedStorageFile.GetUserStoreForAssembly();

            IsolatedStorageFileStream streamWriter = new IsolatedStorageFileStream("X10Communicator.xml", FileMode.Create, isoStorage);
            XmlTextWriter listXmlWriter = new  XmlTextWriter(streamWriter, null);
            XmlSerializer listSerializer = new XmlSerializer(list.GetType());
            listSerializer.Serialize(listXmlWriter, list);
            listXmlWriter.Close();
            streamWriter.Close();
        }

        private static void TurnOffLights(bool removeFromList)
        {
            List<DeviceSetting> list;
            list = getSavedSettings();
            if (list.Count == 0)
            {
                return;
            }
            Firecracker firecracker = Firecracker.GetInstance(1);
            foreach (DeviceSetting item in list)
            {
                char hc = item.Key.Split('|')[0][0];
                int dc;
                int.TryParse(item.Key.Split('|')[1], out dc);

                firecracker.SendCommand(hc, dc, Firecracker.Commands.TurnOff);
            }

            if(removeFromList)
            {
                list.Clear();
                saveSettings(list);
            }
             
        }

        private static void showHelp()
        {
            Console.WriteLine("X10Communicator");
            Console.WriteLine("");
            Console.WriteLine("Usage: x10communicator -hc:<A-P> -dc:<1-16> -c:<0-1>");
            Console.WriteLine("    -hc:    Specifies HouseCode. Valid values are A - P");
            Console.WriteLine("    -dc:    Specicies DeviceCode. Valid values are 1-16");
            Console.WriteLine("    -c:     Specifies the action.  1 = TurnOn, 2 = TurnOff");
            Console.WriteLine("  start     Uses saved values to restore devices before they were shutdown");
            Console.WriteLine("  shutdown  Turns off all devices that were on.  Current state is already saved.");
            Console.WriteLine("  TurnOffOtherDevices   Turns off other devices when turning on another one");
            Console.WriteLine("");
        }
    }
}
